//封装购物车模块

import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useUserStore } from "./user";
import { insertCartAPI,findNewCartListAPI,delCartAPI } from "@/apis/cart";


export const useCartStore = defineStore('cart',()=>{
const userStore = useUserStore()
const isLogin = computed(()=>userStore.userInfo.token)

  //定义购物车state

  const cartList = ref([])
  //定义购物车action
  const addCart = async (goods)=>{
    if(isLogin.value){
      //登录之后的加购物车逻辑
      debugger
      const {skuId,count} = goods
      await insertCartAPI({skuId,count})

      const res = await findNewCartListAPI()
      cartList.value = res.result
    }else{
      const item = cartList.value.find((item) => goods.skuId === item.skuId)
      if(item){
        item.count++
      }else{
        cartList.value.push(goods)
      }
    }
  }

  const delCart =async (skuId) =>{
    if(isLogin.value){
      await delCartAPI([skuId])
      const res = await findNewCartListAPI()
      cartList.value = res.result
    }else{
      const idx = cartList.value.findIndex((item) => skuId===item.skuId)
      cartList.value.splice(idx,1)
    }

  }

  const singleCheck = (skuId,selected) =>{
    const item = cartList.value.find((item)=>item.skuId === skuId)
    item.selected = selected
  }

  const allCheck = (selected) =>{
    cartList.value.forEach(item=>item.selected=selected)
  }

  const  allCount = computed(()=> cartList.value.reduce((a,c)=>a+c.count,0))
  const  allPrice = computed(()=> cartList.value.reduce((a,c)=>a+c.count*c.price,0))

  const selectedCount = computed(()=> cartList.value.filter((item)=>item.selected).reduce((a,c)=>a+c.count,0))
  const selectedPrice = computed(()=> cartList.value.filter((item)=>item.selected).reduce((a,c)=>a+c.count*c.price,0))

  const isAll = computed(()=>cartList.value.every((item)=>item.selected))

  const clearCart = () =>{
    cartList.value = []
  }

  const updateNewList = async ()=>{
    const res = await findNewCartListAPI()
    cartList.value = res.result
  }
  return {
    cartList,
    addCart,
    delCart,
    allCount,
    allPrice,
    isAll,
    singleCheck,
    allCheck,
    selectedCount,
    selectedPrice,
    clearCart,
    updateNewList
  }
},{
  persist: true
})
